/*
 * @Author: 小巴 2393953821@qq.com
 * @Date: 2024-05-30 14:24:14
 * @LastEditors: 小巴 2393953821@qq.com
 * @LastEditTime: 2024-06-20 16:09:32
 * @FilePath: \drgs_web\src\utils\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 500000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {

    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data
    // console.log("执行"+JSON.stringify(res))
    if(response.config.responseType === 'arraybuffer') {
      return response;
    }
   
    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 201 && res.status !== 200 && response.config.responseType !== 'arraybuffer') {
      Message({
        message: res.msg || '网络异常，请重试！',
        type: 'error',
        duration: 5 * 1000
      })
      if(res.status == 401){
        Message({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
        return false
      }
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.status === 50008 || res.status === 50012 || res.status === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if(res.status === 802) {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
          return
        })
      }
      return Promise.reject(new Error(res.msg || '网络异常，请重试！'))
    } else {
      return res
    }
  },
  error => {
    // console.log('err' + error) // for debug
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
